package com.zqxx.examine.management.controller.action.teacher;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.zqxx.examine.common.utils.QuestionAdapter;
import com.zqxx.examine.management.security.UserInfo;
import com.zqxx.examine.management.service.ExamPaperService;
import com.zqxx.examine.management.service.QuestionService;
import com.zqxx.examine.model.exam.AnswerSheet;
import com.zqxx.examine.model.exam.AnswerSheetItem;
import com.zqxx.examine.model.exam.ExamPaper;
import com.zqxx.examine.model.exam.Message;
import com.zqxx.examine.model.exam.PaperCreatorParam;
import com.zqxx.examine.model.question.QuestionQueryResult;
import com.zqxx.examine.model.question.QuestionStruts;

@Controller
public class ExamPaperActionTeacher
{
  @Autowired
  private ExamPaperService examPaperService;
  @Autowired
  private QuestionService questionService;
  
  @RequestMapping(value={"teacher/exampaper-add"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message createExamPaper(@RequestBody PaperCreatorParam param)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Message message = new Message();
    ExamPaper examPaper = new ExamPaper();
    examPaper.setName(param.getPaperName());
    examPaper.setDuration(param.getTime());
    examPaper.setPass_point(param.getPassPoint());
    examPaper.setField_id(param.getPaperType());
    examPaper.setCreator(userInfo.getUsername());
    examPaper.setTotal_point(param.getPaperPoint());
    examPaper.setIs_subjective(true);
    if (param.getQuestionKnowledgePointRate().size() == 0)
    {
      try
      {
        this.examPaperService.insertExamPaper(examPaper);
      }
      catch (Exception ex)
      {
        message.setResult(ex.getMessage());
      }
      message.setGeneratedId(examPaper.getId());
      return message;
    }
    List<Integer> idList = new ArrayList();
    

    HashMap<Integer, Float> knowledgeMap = param.getQuestionKnowledgePointRate();
    Iterator<Integer> it = knowledgeMap.keySet().iterator();
    while (it.hasNext()) {
      idList.add(it.next());
    }
    HashMap<Integer, HashMap<Integer, List<QuestionStruts>>> questionMap = this.questionService.getQuestionStrutsMap(idList);
    try
    {
      this.examPaperService.createExamPaper(questionMap, param.getQuestionTypeNum(), param
        .getQuestionTypePoint(), param
        .getQuestionKnowledgePointRate(), examPaper);
      message.setGeneratedId(examPaper.getId());
    }
    catch (Exception e)
    {
      e.printStackTrace();
      message.setResult(e.getMessage());
    }
    return message;
  }
  
  @RequestMapping(value={"/teacher/exampaper/get-question-detail4add"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public List<QuestionQueryResult> getQuestion5add(Model model, HttpServletRequest request, @RequestBody List<Integer> idList)
  {
    String strUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
    
  /*  Set<Integer> set = new TreeSet();
    for (Iterator localIterator1 = idList.iterator(); localIterator1.hasNext();)
    {
      int id = ((Integer)localIterator1.next()).intValue();
      set.add(Integer.valueOf(id));
    }
    idList.clear();
    Object it = set.iterator();
    while (((Iterator)it).hasNext()) {
      idList.add(((Iterator)it).next());
    }*/
    List<QuestionQueryResult> returnList = this.questionService.getQuestionDescribeListByIdList(idList);
    for (QuestionQueryResult question : returnList)
    {
      QuestionAdapter adapter = new QuestionAdapter(question, strUrl);
      question.setContent(adapter.getStringFromXML());
    }
    return returnList;
  }
  
  @RequestMapping(value={"/teacher/exampaper/update-exampaper/{examPaperId}"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message exampaperOnUpdate(Model model, @PathVariable("examPaperId") int examPaperId, @RequestBody HashMap<Integer, Float> questionPointMap)
  {
    Message message = new Message();
    try
    {
      ExamPaper examPaper = new ExamPaper();
      List<Integer> idList = new ArrayList();
      Iterator<Integer> it = questionPointMap.keySet().iterator();
      float sum = 0.0F;
      while (it.hasNext())
      {
        int key = ((Integer)it.next()).intValue();
        idList.add(Integer.valueOf(key));
      }
      List<QuestionQueryResult> questionList = this.questionService.getQuestionDescribeListByIdList(idList);
      AnswerSheet as = new AnswerSheet();
      as.setExamPaperId(examPaperId);
      List<AnswerSheetItem> asList = new ArrayList();
      for (QuestionQueryResult q : questionList)
      {
        AnswerSheetItem item = new AnswerSheetItem();
        item.setAnswer(q.getAnswer());
        item.setQuestionId(q.getQuestionId());
        item.setPoint(((Float)questionPointMap.get(Integer.valueOf(q.getQuestionId()))).floatValue());
        item.setQuestionTypeId(q.getQuestionTypeId());
        q.setQuestionPoint(((Float)questionPointMap.get(Integer.valueOf(q.getQuestionId()))).floatValue());
        sum += ((Float)questionPointMap.get(Integer.valueOf(q.getQuestionId()))).floatValue();
        asList.add(item);
      }
      as.setPointMax(sum);
      as.setAnswerSheetItems(asList);
      Gson gson = new Gson();
      String content = gson.toJson(questionList);
      String answerSheet = gson.toJson(as);
      examPaper.setAnswer_sheet(answerSheet);
      examPaper.setContent(content);
      examPaper.setTotal_point(sum);
      examPaper.setId(examPaperId);
      



      this.examPaperService.updateExamPaper(examPaper);
    }
    catch (Exception e)
    {
      message.setResult(e.getLocalizedMessage());
    }
    return message;
  }
  
  @RequestMapping(value={"teacher/exampaper/paper-delete"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message deleteExamPaper(@RequestBody Integer examPaperId)
  {
    Message message = new Message();
    try
    {
      ExamPaper examPaper = this.examPaperService.getExamPaperById(examPaperId.intValue());
      if (examPaper.getStatus() == 1)
      {
        message.setResult("已发布的试卷不允许删除");
        return message;
      }
      this.examPaperService.deleteExamPaper(examPaperId.intValue());
    }
    catch (Exception e)
    {
      message.setResult(e.getClass().getName());
    }
    return message;
  }
  
  @RequestMapping(value={"teacher/exampaper/create-doc-{examPaperId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  @ResponseBody
  public Message createDocPaper(@PathVariable("examPaperId") int examPaperId)
  {
    Message msg = new Message();
    
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String dateStr = new SimpleDateFormat("yyyyMMddhh24mmss").format(new Date());
    
    String filePath = System.getProperty("catalina.base") + ",webapps,files,tmp," + userInfo.getUsername() + "," + dateStr;
    String relativePath = "files,tmp," + userInfo.getUsername() + "," + dateStr;
    ExamPaper examPaper = this.examPaperService.getExamPaperById(examPaperId);
    try
    {
      this.examPaperService.generateDoc(examPaper, filePath.replace(",", File.separator));
      msg.setMessageInfo((relativePath + "," + examPaper.getName() + ".docx").replace(",", File.separator));
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return msg;
  }
}
